<template>
  <div>
    <el-switch v-model="draggable" active-text="开启拖拽" inactive-text="关闭拖拽"></el-switch>
    <el-button v-if="draggable" @click="batchSave">批量保存</el-button>
    <el-button type="danger" @click="batchDelete">批量删除</el-button>
    <el-tree :data="data"
             :props="defaultProps"
             show-checkbox
             node-key="catId"
             :default-expanded-keys="expandedKey"
             :expand-on-click-node="false"
             :draggable="draggable"
             :allow-drop="allowDrop"
             @node-drop="handleDrop"
             ref="menuTree">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => append(data)">
            添加
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="() => edit(data)">
            修改
          </el-button>
          <el-button
            type="text"
            size="mini"
            v-if="node.childNodes.length == 0"
            @click="() => remove(node, data)">
            删除
          </el-button>
        </span>
      </span>
    </el-tree>
    <el-dialog :title="dialogTitle"
               :before-close="handleClose"
               :close-on-click-modal="false"
               :visible.sync="dialogCategoryVisible" width="35%">
      <el-form :model="categoryForm">
        <el-form-item label="分类名称：" label-width="100px">
          <el-input v-model="categoryForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标：" label-width="100px">
          <el-input v-model="categoryForm.icon" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="计量单位：" label-width="100px">
          <el-input v-model="categoryForm.productUnit" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="handleCategory">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        maxLevel: 0,
        pCid: [],
        draggable: false,
        updateNodes: [],
        dialogTitle: '',
        categoryForm: {
          catId: '',
          name: '',
          icon: '',
          productUnit: '',
          parentCid: '',
          catLevel: '',
          sort: 0,
          showStatus: 1,
        },
        handleType: '',
        dialogCategoryVisible: false,
        data: [],
        expandedKey: [],
        defaultProps: {
          children: 'children',
          label: 'name'
        }
      }
    },
    created() {
      this.getMenus()
    },
    methods: {
      batchDelete() {
        let catIds = [];
        let catNames = [];
        let checkedNodes = this.$refs.menuTree.getCheckedNodes();
        console.log("被选中的元素", checkedNodes);
        if(checkedNodes.length <= 0){
          this.$message({
            message: "请先选择菜单",
            type: "info"
          });
          return;
        }
        for (let i = 0; i < checkedNodes.length; i++) {
          catIds.push(checkedNodes[i].catId);
          catNames.push(checkedNodes[i].name);
        }
        this.$confirm(`是否批量删除【${catNames}】菜单?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            this.$http({
              url: this.$http.adornUrl("/product/category/delete"),
              method: "post",
              data: this.$http.adornData(catIds, false)
            }).then(({ data }) => {
              this.$message({
                message: "菜单批量删除成功",
                type: "success"
              });
              this.getMenus();
            });
          })
          .catch(() => {});
      },
      batchSave() {
        this.$http({
          url: this.$http.adornUrl("/product/category/update/sort"),
          method: "post",
          data: this.$http.adornData(this.updateNodes, false)
        }).then(({ data }) => {
          this.$message({
            message: "菜单顺序等修改成功",
            type: "success"
          });
          //刷新出新的菜单
          this.getMenus();
          //设置需要默认展开的菜单
          this.expandedKey = this.pCid;
          this.updateNodes = [];
          this.maxLevel = 0;
          // this.pCid = 0;
        });
      },
      handleDrop(draggingNode, dropNode, dropType, ev) {
        console.log("handleDrop: ", draggingNode, dropNode, dropType);
        //1、当前节点最新的父节点id
        let pCid = 0;
        let siblings = null;
        if (dropType == "before" || dropType == "after") {
          pCid =
            dropNode.parent.data.catId == undefined
              ? 0
              : dropNode.parent.data.catId;
          siblings = dropNode.parent.childNodes;
        } else {
          pCid = dropNode.data.catId;
          siblings = dropNode.childNodes;
        }
        this.pCid.push(pCid);

        //2、当前拖拽节点的最新顺序，
        for (let i = 0; i < siblings.length; i++) {
          if (siblings[i].data.catId == draggingNode.data.catId) {
            //如果遍历的是当前正在拖拽的节点
            let catLevel = draggingNode.level;
            if (siblings[i].level != draggingNode.level) {
              //当前节点的层级发生变化
              catLevel = siblings[i].level;
              //修改他子节点的层级
              this.updateChildNodeLevel(siblings[i]);
            }
            this.updateNodes.push({
              catId: siblings[i].data.catId,
              sort: i,
              parentCid: pCid,
              catLevel: catLevel
            });
          } else {
            this.updateNodes.push({ catId: siblings[i].data.catId, sort: i });
          }
        }

        //3、当前拖拽节点的最新层级
        console.log("updateNodes", this.updateNodes);
      },
      updateChildNodeLevel(node) {
        if (node.childNodes.length > 0) {
          for (let i = 0; i < node.childNodes.length; i++) {
            var cNode = node.childNodes[i].data;
            this.updateNodes.push({
              catId: cNode.catId,
              catLevel: node.childNodes[i].level
            });
            this.updateChildNodeLevel(node.childNodes[i]);
          }
        }
      },
      allowDrop(draggingNode, dropNode, type) {
        //1、被拖动的当前节点以及所在的父节点总层数不能大于3

        //1）、被拖动的当前节点总层数
        console.log("allowDrop:", draggingNode, dropNode, type);
        //
        this.countNodeLevel(draggingNode);
        //当前正在拖动的节点+父节点所在的深度不大于3即可
        let deep = Math.abs(this.maxLevel - draggingNode.level) + 1;
        console.log("深度：", deep);

        //   this.maxLevel
        if (type == "inner") {
          // console.log(
          //   `this.maxLevel：${this.maxLevel}；draggingNode.data.catLevel：${draggingNode.data.catLevel}；dropNode.level：${dropNode.level}`
          // );
          return deep + dropNode.level <= 3;
        } else {
          return deep + dropNode.parent.level <= 3;
        }
      },
      countNodeLevel(node) {
        //找到所有子节点，求出最大深度
        if (node.childNodes != null && node.childNodes.length > 0) {
          for (let i = 0; i < node.childNodes.length; i++) {
            if (node.childNodes[i].level > this.maxLevel) {
              this.maxLevel = node.childNodes[i].level;
            }
            this.countNodeLevel(node.childNodes[i]);
          }
        }
      },
      handleClose() {
        this.categoryForm.catId = '';
        this.categoryForm.name = '';
        this.categoryForm.icon = '';
        this.categoryForm.productUnit = '';
        this.categoryForm.parentCid = '';
        this.categoryForm.catLevel = '';
        this.dialogCategoryVisible = false;
      },
      handleCategory(){
        if(this.handleType === 'add'){
          this.addCategory();
        }
        if(this.handleType === 'edit'){
          this.editCategory();
        }
      },
      addCategory() {
        this.$http({
          url: this.$http.adornUrl('/product/category/save'),
          method: 'post',
          data: this.$http.adornData(this.categoryForm, false)
        }).then(({data}) => {
        if (data && data.code === 0) {
          this.$message({
            message: '新增成功',
            type: 'success',
            duration: 1500,
            onClose: () => {}
          });
          this.getMenus();
          this.expandedKey = [this.categoryForm.parentCid];
          this.handleClose();
        } else {
          this.$message.error(data.msg)
        }
        }).catch(() => {})
      },
      editCategory() {
        let {catId,name,icon,productUnit} = this.categoryForm;
        this.$http({
          url: this.$http.adornUrl('/product/category/update'),
          method: 'post',
          data: this.$http.adornData({catId,name,icon,productUnit}, false)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$message({
              message: '修改成功',
              type: 'success',
              duration: 1500,
              onClose: () => {}
            });
            this.getMenus();
            this.expandedKey = [this.categoryForm.parentCid];
            this.handleClose();
          } else {
            this.$message.error(data.msg)
          }
        }).catch(() => {})
      },
      handleNodeClick(data) {
      },
      getMenus() {
        this.$http({
          url: this.$http.adornUrl('/product/category/list/tree'),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.data = data.data
          } else {
            this.data = []
          }
        })
      },
      edit(data) {
        console.log("修改节点",data);
        this.$http({
          url: this.$http.adornUrl(`/product/category/info/${data.catId}`),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.categoryForm.catId = data.data.catId;
            this.categoryForm.parentCid = data.data.parentCid;
            this.categoryForm.name = data.data.name;
            this.categoryForm.icon = data.data.icon;
            this.categoryForm.productUnit = data.data.productUnit;
          } else {
            this.categoryForm.catId = '';
            this.categoryForm.parentCid = '';
            this.categoryForm.name = '';
            this.categoryForm.icon = '';
            this.categoryForm.productUnit = '';
          }
        })
        this.dialogCategoryVisible = true;
        this.handleType = 'edit';
        this.dialogTitle = '修改分类';
      },
      append(data) {
        console.log("添加节点",data);
        this.categoryForm.parentCid = data.catId;
        this.categoryForm.catLevel = data.catLevel*1+1;
        this.dialogCategoryVisible = true;
        this.handleType = 'add';
        this.dialogTitle = '添加分类';
      },
      remove(node, data) {
        console.log(node,data);
        this.$confirm(`确定要删除${data.name}吗?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl('/product/category/delete'),
            method: 'post',
            data: this.$http.adornData([data.catId], false)
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                }
              });
              this.getMenus();
              this.expandedKey = [node.parent.data.catId];
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {});
      },
    }
  }
</script>
